using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using Ionic.Zip;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.CrystalReports;
using CrystalDecisions.Shared;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;

public partial class DownloadFile : System.Web.UI.Page
{
    ReportDocument repDoc;
    protected univNETLib currentNetLib;
    protected univBanco currentBanco;
    string serverName = "", userId = "", password = "", mfiltro = "",rel_codigo ;
    protected void Page_Load(object sender, EventArgs e)
    {
        currentNetLib = (univNETLib)Session[modzGeneral.mUsu_codigo + "NetLib"];
        currentBanco = (univBanco)Session[modzGeneral.mUsu_codigo + "Banco"];

        System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(((univNETLib)Session[modzGeneral.mUsu_codigo + "NetLib"]).Idioma);
        System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(((univNETLib)Session[modzGeneral.mUsu_codigo + "NetLib"]).Idioma);
        
        string expType = Request.QueryString["type"].ToString();
        string name = Request.QueryString["name"].ToString();
        string driwdown = Request.QueryString["driwdown"].ToString();
        rel_codigo = Request.QueryString["rel_codigo"].ToString();
        try
        {
            name = HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8).Replace("+", "%20");

            repDoc = new ReportDocument();  //(ReportDocument)Session["XRT_Report"];
            repDoc.Load(Session["XRT_Report"].ToString());   
            setLogonDataBase();
            mfiltro = getFiltroCorrente();
            iniciaParametros();
            //CrystalReportViewer1.ReportSource = repDoc;
            //CrystalReportViewer1.DataBind();
            //CrystalReportViewer1.ShowFirstPage();

            if (driwdown == "S")
            {
                Sections crSections2 = repDoc.ReportDefinition.Sections;
                bool subrep = false;
                foreach (Section crSection in crSections2)
                {
                    ReportObjects crReportObjects = crSection.ReportObjects;
                    foreach (ReportObject crReportObject in crReportObjects)
                    {
                        if (crReportObject.Kind == ReportObjectKind.SubreportObject)
                        {
                            SubreportObject crSubreportObject = (SubreportObject)crReportObject;
                            crSubreportObject.EnableOnDemand = (driwdown != "S");
                            crSubreportObject.Width = 1000000;
                            subrep = (driwdown == "S");
                        }
                    }
                    if (subrep)
                    {
                        foreach (ReportObject crReportObject in crReportObjects)
                        {
                            if (crReportObject.Kind != ReportObjectKind.SubreportObject)
                            {
                               try
                                {
                                    crReportObject.Width = 0;
                                    crReportObject.Height = 0;
                                }
                                catch
                                {
                                    try { ((BoxObject)crReportObject).Right = 0; }
                                    catch { }
                                }
                                

                            }
                        }
                    }
                    else
                    {
                        /*foreach (ReportObject crReportObject in crReportObjects)
                        {

                            try
                            {
                                crReportObject.Width = 0;
                                crReportObject.Height = 0;
                            }
                            catch
                            {
                                try { ((BoxObject)crReportObject).Right = 0; }
                                catch { }
                            }

                        }*/
                        try { crSection.SectionFormat.EnableSuppress=true;}
                        catch { }
                    }
                }
            }

            //System.Web.HttpContext.Current.Session.Remove("XRT_Report");


            if (expType == "EXCEL")
                repDoc.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.Excel, Response, true, name);
            else
            {
                repDoc.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, (expType == "PDF"), name);
            }
        }
        catch
        {
            HttpContext.Current.Response.End();
        }

        if (expType != "PRINT")
            HttpContext.Current.Response.End();

    }

    private void setDataBaseUser()
    {
        string[] connectionStr = currentBanco.ConnectionString.Split(';');

        for (int j = 0; j < connectionStr.Length; j++)
        {
            string temp = connectionStr[j];
            if (temp.ToUpper().IndexOf("DATA SOURCE") > -1)
            { serverName = temp.Split('=')[1]; }

            if (temp.ToUpper().IndexOf("USER ID") > -1)
            { userId = temp.Split('=')[1]; }

            if (temp.ToUpper().IndexOf("PASSWORD") > -1)
            { password = temp.Split('=')[1]; }
        }
    }
    private void setLogonDataBase()
    {
        setDataBaseUser();

        //repDoc.SetDatabaseLogon(userId, password, serverName, "");

        //for (int i = 0; i <= repDoc.Subreports.Count - 1; i++)
        //{
        //    repDoc.Subreports[i].SetDatabaseLogon(userId, password, serverName, "");
        //}

        System.Data.Odbc.OdbcConnection cn;
        cn = new System.Data.Odbc.OdbcConnection("dsn=" + serverName + ";UID=" + userId + ";PWD=" + password + ";");
        try
        {
            cn.Open();
            //setNameReport();
        }
        catch (Exception err)
        {
            modzGeneral.MsgBox(err.Message, "dsn=" + serverName + ";UID=" + userId + ";PWD=*******;");
        }
        cn.Close();
        cn.Dispose();

        foreach (ReportDocument subrpt in repDoc.Subreports)
        {
            try
            {
                subrpt.DataSourceConnections[0].SetConnection(serverName, "", userId, password);
            }
            catch { }

        }
        //repDoc.SetDatabaseLogon(userId, password, serverName, "");
        repDoc.DataSourceConnections[0].SetConnection(serverName, "", userId, password);
    }
    protected string getFiltroCorrente()
    {

        string sql = "select filtroselect from web_grid_state where usu_codigo = '" +
            currentNetLib.usu_codigo + "' and branch_id = 'SR_" + rel_codigo + "'";

        string filtro = currentBanco.SelectInto(sql);

        return filtro;
    }
    private void iniciaParametros()
    {
        string sql = "select parametro, valor, valor_auxiliar from web_filtro " +
            " where branch_id = 'SR_" + rel_codigo + "' " +
            " and usu_codigo = '" + currentNetLib.usu_codigo + "' " +
            " and nome = '" + mfiltro + "'";

        OracleDataReader reader;
        currentBanco.OpenRecordSet(sql, out reader);

        CrystalReportViewer1.Page.Culture = currentNetLib.Idioma;
        CrystalReportViewer1.Page.UICulture = currentNetLib.Idioma;

        ParameterValues xyvals = new ParameterValues();
        ParameterDiscreteValue xyDiscrete = new ParameterDiscreteValue();

        int cnt = repDoc.DataDefinition.ParameterFields.Count;
        for (int i = 0; i < cnt; i++)
        {
            if (!repDoc.DataDefinition.ParameterFields[i].IsLinked())
            {
                ParameterValues myvals = new ParameterValues();
                ParameterDiscreteValue myDiscrete = new ParameterDiscreteValue();

                switch (repDoc.DataDefinition.ParameterFields[i].ParameterValueKind)
                {
                    case CrystalDecisions.Shared.ParameterValueKind.DateTimeParameter:
                        myDiscrete.Value = DateTime.Now;
                        break;

                    case CrystalDecisions.Shared.ParameterValueKind.BooleanParameter:
                        myDiscrete.Value = false;
                        break;
                    case CrystalDecisions.Shared.ParameterValueKind.DateParameter:
                        myDiscrete.Value = DateTime.Now;
                        break;
                    case CrystalDecisions.Shared.ParameterValueKind.NumberParameter:
                        myDiscrete.Value = 0;
                        break;
                    case CrystalDecisions.Shared.ParameterValueKind.StringParameter:
                        myDiscrete.Value = "";
                        break;
                }
                myvals.Add(myDiscrete);
                repDoc.DataDefinition.ParameterFields[i].ApplyCurrentValues(myvals);
            }
        }

        while (reader.Read())
        {
            ParameterValues myvals = new ParameterValues();
            ParameterDiscreteValue myDiscrete = new ParameterDiscreteValue();

            switch (repDoc.DataDefinition.ParameterFields[reader[0].ToString()].ParameterValueKind)
            {
                case CrystalDecisions.Shared.ParameterValueKind.DateTimeParameter:
                    try
                    {
                        myDiscrete.Value = Convert.ToDateTime(reader[1].ToString());
                    }
                    catch
                    {
                        myDiscrete.Value = DateTime.Now;
                    }
                    break;

                case CrystalDecisions.Shared.ParameterValueKind.BooleanParameter:
                    myDiscrete.Value = bool.Parse(reader[1].ToString());
                    break;
                case CrystalDecisions.Shared.ParameterValueKind.DateParameter:
                    try
                    {
                        myDiscrete.Value = Convert.ToDateTime(reader[1].ToString());
                    }
                    catch
                    {
                        myDiscrete.Value = DateTime.Now;
                    }
                    break;
                case CrystalDecisions.Shared.ParameterValueKind.NumberParameter:
                    myDiscrete.Value = int.Parse(reader[1].ToString());
                    break;
                case CrystalDecisions.Shared.ParameterValueKind.StringParameter:
                    myDiscrete.Value = Convert.ToString((reader[1].ToString()));
                    break;
            }
            myvals.Add(myDiscrete);
            repDoc.DataDefinition.ParameterFields[reader[0].ToString()].ApplyCurrentValues(myvals);

            foreach (ReportDocument subrpt in repDoc.Subreports)
            {
                try
                {
                    myvals = new ParameterValues();
                    myDiscrete = new ParameterDiscreteValue();

                    switch (subrpt.DataDefinition.ParameterFields[reader[0].ToString()].ParameterValueKind)
                    {
                        case CrystalDecisions.Shared.ParameterValueKind.DateTimeParameter:
                            try
                            {
                                myDiscrete.Value = Convert.ToDateTime(reader[1].ToString());
                            }
                            catch
                            {
                                myDiscrete.Value = DateTime.Now;
                            }
                            break;

                        case CrystalDecisions.Shared.ParameterValueKind.BooleanParameter:
                            myDiscrete.Value = bool.Parse(reader[1].ToString());
                            break;
                        case CrystalDecisions.Shared.ParameterValueKind.DateParameter:
                            try
                            {
                                myDiscrete.Value = Convert.ToDateTime(reader[1].ToString());
                            }
                            catch
                            {
                                myDiscrete.Value = DateTime.Now;
                            }
                            break;
                        case CrystalDecisions.Shared.ParameterValueKind.NumberParameter:
                            myDiscrete.Value = int.Parse(reader[1].ToString());
                            break;
                        case CrystalDecisions.Shared.ParameterValueKind.StringParameter:
                            myDiscrete.Value = Convert.ToString((reader[1].ToString()));
                            break;
                    }
                    myvals.Add(myDiscrete);
                    subrpt.DataDefinition.ParameterFields[reader[0].ToString()].ApplyCurrentValues(myvals);

                }
                catch { }

                xyDiscrete.Value = currentNetLib.usu_codigo.ToUpper();
                xyvals.Add(xyDiscrete);
                try
                {
                    subrpt.DataDefinition.ParameterFields["USU_CODIGO"].ApplyCurrentValues(xyvals);
                }
                catch { }


            }

        }

        xyDiscrete.Value = currentNetLib.usu_codigo.ToUpper();
        xyvals.Add(xyDiscrete);
        try { repDoc.DataDefinition.ParameterFields["USU_CODIGO"].ApplyCurrentValues(xyvals); }
        catch { }


        reader.Close();

    }
}
